﻿/******************************************************************************
 * Copyright (C) 2015  671643387@qq.com
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *****************************************************************************/

#include <cstdio>
#include <cstdarg>
#if defined(_WINDOWS)
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <strsafe.h>
#include <DbgHelp.h>
#pragma warning(disable:4995)
#endif // _WINDOWS
#include <NodeCpp/ErrorHandler.h>
#include <NodeCpp/Util/Application.h>
#include <NodeCpp/String.h>
#include "Shared/Log/Log.h"

namespace NodeCpp {

	void ErrorHandler::HandleException(std::exception& e)
    {
		sLog.outError("exception: %s\n", e.what());
    }

    void ErrorHandler::HandleSystemException(void)
    {
        sLog.outError("HandleSystemException\n");
    }


    namespace Util {

#if defined(_WINDOWS)

        LONG Application::UnhandledExceptionFilter(struct _EXCEPTION_POINTERS* _ExpPointer)
        {
            TCHAR szDumpPath[MAX_PATH], szDumpFile[MAX_PATH];
            GetCurrentDirectory(MAX_PATH, szDumpPath);
            StringCbPrintf(szDumpFile, MAX_PATH, TEXT("%s\\Realmd.dmp"), szDumpPath);

            HANDLE hFile = CreateFile(szDumpFile,
                GENERIC_WRITE,
                0,
                NULL,
                CREATE_ALWAYS,
                0,
                NULL);

            _MINIDUMP_EXCEPTION_INFORMATION   ExInfo;
            ExInfo.ThreadId = GetCurrentThreadId();
            ExInfo.ExceptionPointers = _ExpPointer;
            ExInfo.ClientPointers = NULL;

            MiniDumpWriteDump(GetCurrentProcess(),
                GetCurrentProcessId(),
                hFile,
                MiniDumpWithFullMemory,
                &ExInfo,
                NULL,
                NULL);

            return EXCEPTION_EXECUTE_HANDLER;
        }

#endif // _WINDWOS
    }
}

#define DB_ERROR_LINE_SIZE	0x1000
void __OnLoginDBError(int _Id, const char* _Format, ...)
{
	char _Msg[DB_ERROR_LINE_SIZE];
	std::va_list _Ap;
	va_start(_Ap, _Format);
	NodeCpp::vsnprintf(_Msg, DB_ERROR_LINE_SIZE, _Format, _Ap);
	va_end(_Ap);

	sLog.outDbError(_Msg);
}